package com.stone.sys.action;

/**
 * <pre>
 * ���ڣ�Jul 16, 2009
 * </pre>
 */

import java.util.HashMap;
import java.util.List;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import com.stone.para.IConstant;
import com.stone.sys.pojo.TDictionary;
import com.stone.sys.pojo.TUser;
import com.stone.sys.service.DictionaryService;
import com.stone.sys.service.UserService;
import com.stone.utils.JsonUtils;
import com.stone.utils.StringUtils;

import frm.ssh.action.BaseListAction;
import frm.ssh.exception.AppException;
import frm.ssh.util.SpringUtil;
import frm.ssh.util.page.CustomPage;

public class UserListAction extends BaseListAction {

	private static final long serialVersionUID = 3979577965804736350L;
	
	private String start;
	private String limit;
	private String organCode;
	private String roleID;
	
	private String userid;
	private String username;
	private String organid;
    private String organcid;
	
	public String getOrgancid() {
		return organcid;
	}

	public void setOrgancid(String organcid) {
		this.organcid = organcid;
	}

	// 人员类别
	private List<TDictionary> rylbList;
	
    /** * 构造方法. */
    public UserListAction() {
        this.entityClass = TUser.class;
    }

	public String getOrganCode() {
		return organCode;
	}

	public void setOrganCode(String organCode) {
		this.organCode = organCode;
	}

	private UserService userService;
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.service = userService;
		this.userService = userService;
	}

	/**
	 * 设置查询条件
	 */
	public HashMap<String, Object> setSearchCondition() {
		
		HashMap<String, Object> m = new HashMap<String, Object>();
		m.put("cols", "new map(user.id as id, user.loginId as loginId,user.name as name, user.mobile as nobile, user.state as state)");//, dic.itemName as rylbname
		m.put("alias", "user");//, TDictionary dic
		m.put("join", "");//" LEFT JOIN user.organ o ");
		//m.put("orderBy","user.id");
		
		String conditions = "1=1";//"user.rylb = dic.id and dic.itemType = 'RYLB'";// user.organId in(select a.id from TOrgan a where a.organCode like '" + super.getSearchBean().getCon1() + "%')";// '"+super.getSearchBean().getCon1()+"'");

		// 当前用户上级部门
		String organCode = String.valueOf(super.getSession().getAttribute(IConstant.SESSION_TORGAN_CODE));
		String o = organCode.substring(0, (organCode.length() > 3 ? organCode.length() - 3 : 3));
		
		if (StringUtils.isNullOrBlank(super.getSearchBean().getCon1())) {
			conditions += " and user.organ.organCode like '" + o + "%'";//" (o.organCode like '" + o + "%' or o.organCode is null)";// '"+super.getSearchBean().getCon1()+"'");
		} else {
			conditions += " and user.organ.organCode like '" + super.getSearchBean().getCon1() + "%'";//" (o.organCode like '" + super.getSearchBean().getCon1() + "%' or o.organCode is null)";
		}
		
		if (!StringUtils.isNullOrBlank(super.getSearchBean().getCon2())) {
			conditions += " and user.loginId like '%" + super.getSearchBean().getCon2() + "%'";
		}
		
		if (!StringUtils.isNullOrBlank(super.getSearchBean().getCon3())) {
			conditions += " and user.name like '%" + super.getSearchBean().getCon3() + "%'";
		}
		
//		if (super.getSearchBean().getCon5() == null) {
//			super.getSearchBean().setCon5("");
//		}
		
		if (!StringUtils.isNullOrBlank(super.getSearchBean().getCon5())) {
			conditions += " and user.state = '" + super.getSearchBean().getCon5() + "'";
		}
		
//		if (!StringUtils.isNullOrBlank(super.getSearchBean().getCon4())) {
//			conditions += " and user.rylb = '" + super.getSearchBean().getCon4() + "'";
//		}
		
		// 查询条件
		//m.put("conditions", "".equals(super.getSearchBean().getCon1())? "user.loginId <> 'admin'":"user.loginId <> 'admin' and user.organId = '"+super.getSearchBean().getCon1()+"'");
		m.put("conditions",conditions);//conditions);
		m.put("clause", " order by user.sortid");
		
		// 人员类型
		//DictionaryService dicService = (DictionaryService) SpringUtil.getInstance().getBean("dicService");
		//rylbList = dicService.findList("RYLB");
	
		return m;
		
	}
	
	/**
	 * 初次进入用户页面
	 * 
	 * @return
	 * @throws AppException
	 */
	public String initList() throws Exception {
		//System.out.println("countPerPage2=="+super.getParameter("countPerPage"));
		this.setSessionAttribute("countPerPage", Integer.valueOf(super.getParameter("countPerPage")));
		return "USER_FRAME_SUCCESS";
	}
	
	/**
	 * 用户授权时的ExtGrid查询
	 * 
	 * @return
	 * @throws AppException
	 */
	public void getListExt() throws Exception {

		super.setPage((String.valueOf((Integer.parseInt(getStart()) / Integer.parseInt(getLimit()) + 1))));
		
		HashMap<String, Object> m = new HashMap<String, Object>();
		
		String cols = " user.id as id, user.loginId as loginId, user.name as name, user.isadmin as isadmin,";
		
		if (!StringUtils.isNullOrBlank(roleID) && !"0".equals(roleID)) {
			cols += "(select count(ur.id) from TUserRole ur where ur.userId = user.id and roleId = " + roleID + ") as userCount";
		} else {
			cols += "(0) as userCount";
		}
		m.put("cols", cols);//"user, (select count(*) from TUserRole ur where ur.userId = user.id) as count");
		m.put("alias", "user");
		m.put("join", "");//" LEFT JOIN user.organ o");

		String oc = String.valueOf(super.getSession().getAttribute(IConstant.SESSION_TORGAN_CODE));
		
		// 上级部门
		String o = oc.substring(0, (oc.length() > 3 ? oc.length() - 3 : 3));
	
		String conditions = "user.id > 0 ";
		
		// 选中部门的时候查询当前部门
		if (!StringUtils.isNullOrBlank(organCode)) {
			conditions += " and user.organ.organCode like '" + organCode + "%')";// '"+super.getSearchBean().getCon1()+"'");
			
			// 没选中部门查询整个机构
		} else {
			conditions = " and user.organ.organCode like '" + o + "%')";
		}
		m.put("conditions",conditions);//conditions);
		m.put("clause", " order by user.sortid");
		
		// 根据起始记录查询当前页记录
		List<HashMap<String,Object>> list = service.getPageListByDHql(Integer.parseInt(getStart()), Integer.parseInt(getLimit()) , m,this.entityClass.getName() );
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(list, jsonConfig);

		String strTree = "{result:" + json.toString() + ",totalCount:[" + service.getTotalByDHql(conditions, null, this.entityClass.getName() + " as user"  ) + "]}";
		
        super.getResponse().getWriter().print(strTree);
		
	}
	
	/**
	 * 弹出选择的checkbox tree
	 * 
	 * @return
	 * @throws AppException
	 */
	@SuppressWarnings("unchecked")
	public void getListExtTree() throws Exception {

		List<HashMap<String,String>> list = null;
		
		List<HashMap<String,String>> listOrgan = null;
		
		String where = "";

		if ("user".equals(super.getRequest().getParameter("state"))) {

				listOrgan = this.userService.getListByDHql(" 'A' || o.id as id, o.organName as text, o.organCode as qtip, 'A' || o.parentId as parentId", 
																						where,
																						null, 
																						" order by o.organCode", 
																						"TOrgan o");
				
				////where = "u.id > 0 and u.state = '1' ";

				list = this.userService.getListByDHql("u.id as id, u.name as text, 'A' || u.organ.id as parentId, '000' as qtip", 
																						where,
																						null, 
																						" order by u.sortid", 
																						"TUser u");
				
				listOrgan.addAll(list);
		} else if ("bdz".equals(super.getRequest().getParameter("state"))) {

			listOrgan = this.userService.getListByDHql(" o.id as id, o.bdzname as text, o.bdzcode as qtip, 'root' as parentId", 
																					where,
																					null, 
																					" order by o.sortid", 
																					"TBdz o");
			
			
	} 
		else {

			listOrgan = this.userService.getListByDHql(" o.id as id, o.organName as text, o.organCode as qtip,o.parentId as parentId", 
					"",
					null, 
					" order by o.organCode", 
					"TOrgan o");
		}

        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(listOrgan, jsonConfig);

        super.getResponse().getWriter().print(json.toString());
		
	}
	//////////////by wangtao add20110325
	/**
	 * 弹出到位人员选择的checkbox tree
	 * 
	 * @return
	 * @throws AppException
	 */
	@SuppressWarnings("unchecked")
	public void getDwryListExtTree() throws Exception {

		List<HashMap<String,String>> list = null;
		
		List<HashMap<String,String>> listOrgan = null;

		if ("user".equals(super.getRequest().getParameter("state"))) {
			
			String where = "(dydj is null or dydj = '0') and organName != '防误专责人'";
			
			// 钥匙的允许使用人
			if ("1".equals(super.getRequest().getParameter("key"))) {
				where  = "dydj is null or dydj = '0'";
			}
			
			listOrgan = this.userService.getListByDHql(" 'A' || o.id as id, o.organName as text, o.organCode as qtip, 'A' || o.parentId as parentId", 
																					where,
																					null, 
																					" order by o.organCode", 
																					"TOrgan o");
			
			where = " u.id = ur.userId and ur.roleId = r.id and r.nameen in('ZBZ','BZZ','GLRY') and u.id > 0";
			
			// 钥匙的允许使用人
			if ("1".equals(super.getRequest().getParameter("key"))) {
				where  = "u.id > -10";
			}
			
			list = this.userService.getListByDHql("u.id as id, u.name as text, 'A' || u.organ.id as parentId, '000' as qtip", 
																					where,
																					null, 
																					" order by u.sortid", 
																					"TUser u, TUserRole ur , TRole r");
			
			listOrgan.addAll(list);
		
		} else {
			// dydj
			listOrgan = this.userService.getListByDHql(" o.id as id, o.organName as text, o.organCode as qtip,o.parentId as parentId", 
					"organName != '防误专责人'",
					null, 
					" order by o.organCode", 
					"TOrgan o");
		}
		
        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
    	
        JSON json = JSONSerializer.toJSON(listOrgan, jsonConfig);

        super.getResponse().getWriter().print(json.toString());
		
	}
	
//	/**
//	 * 登陆页面的下拉框
//	 * 
//	 * @return
//	 * @throws AppException
//	 */
//	@SuppressWarnings("unchecked")
//	public void getUserListLogin() throws Exception {
//
//		List<HashMap<String,String>> list;
//
//		list = this.userService.getListByDHql("u.loginId as loginId, u.name as name", 
//																			"",
//																			null, 
//																			" order by u.id", 
//																			"TUser u");
//	
//        JsonConfig jsonConfig = JsonUtils.configJson(new String[] {}, "yyyy-MM-dd");
//    	
//        JSON json = JSONSerializer.toJSON(list, jsonConfig);
//
//        super.getResponse().getWriter().print(json.toString());
//		
//	}
	
	private List<HashMap<String,Object>> userList;
	
	public List<HashMap<String, Object>> getUserList() {
		return userList;
	}

	/**
	 * 弹出页面的人员选择
	 * 
	 * @return
	 * @throws AppException
	 */
	@SuppressWarnings("unchecked")
	public String getUserListByRoleCode() throws Exception {
		
		String organCode = String.valueOf(super.getSession().getAttribute(IConstant.SESSION_TORGAN_CODE));
		
		// 是否管理员
		String isAdmin = (String) super.getSession().getAttribute(IConstant.SESSION_ISADMIN);		
		
		// 人员信息
		//String o = super.getRequest().getParameter("organid");
		
		String where = " u.id > 0 ";//u.organ.organCode like '" + organCode + "%'";
		
		// 查询条件OUID很重要
		if (!"1".equals(isAdmin)) {
			where += " and u.state = '1' and u.organ.organCode like '" + organCode + "%'";
		}
		
//		if (!StringUtils.isNullOrBlank(o)) {
//			where += " and (u.organ.id in (" + o + ") or u.organ.parentId in (" + o + "))";
//		}
		
//		String rolecode = super.getRequest().getParameter("rolecode");
//		
//		if (!StringUtils.isNullOrBlank(rolecode)) {
//			where += " and r.rolecode = '" + rolecode + "'";
//		}

		if (!StringUtils.isNullOrBlank(super.getSearchBean().getCon12())) {
			where += " and u.loginId like '%" + super.getSearchBean().getCon12() + "%'";
		}
		
		if (!StringUtils.isNullOrBlank(super.getSearchBean().getCon13())) {
			where += " and u.name like '%" + super.getSearchBean().getCon13() + "%'";
		}
		
		userList = this.userService.getListByDHql("u.id as id, u.name as username, u.organ.organName as organname, u.loginId as loginid", 
																		where,
																		null, 
																		" order by u.sortid", 
																		"TUser u");

		return "USER_POPUP_SUCCESS";
		
	}
	
	public String getStart() {
		return start == null ? "0" : start;
	}

	public void setStart(String start) {
		this.start = start;
	}

	public String getLimit() {
		return limit == null ? String.valueOf(CustomPage.PER_PAGE) : limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public String getRoleID() {
		return roleID;
	}

	public void setRoleID(String roleID) {
		this.roleID = roleID;
	}

	public List<TDictionary> getRylbList() {
		return rylbList;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getOrganid() {
		return organid;
	}

	public void setOrganid(String organid) {
		this.organid = organid;
	}
	
}
